package com.mr.service;

import com.b2c.common.utils.NumberUtils;
import com.mr.mapper.UserMapper;

import com.mr.pojo.User;
import com.mr.utils.Md5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserService
 * @Description: TODO
 * @Author kun
 * @Date 2020/8/26
 * @Version V1.0
 **/
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public Boolean validNameAndPhone(String data,Integer type){
        User user=new User();
        if(type==1){
            user.setUsername(data);
        }else  if(type==2){
            user.setPhone(data);
        }
        return  userMapper.selectCount(user)==0;
    }

    public  Boolean register(User user){
        //获取redis key值
        String key = KEY_PREFIX + user.getPhone();
        //通过key获取验证码
        String code = this.redisTemplate.opsForValue().get(key);
        if (user == null) {
            return false;
        }
        if (user.getCode().equals(code)) {
            //设置注册时间
            user.setCreated(new Date());
            //设置uuid为盐
            user.setSalt(Md5Utils.generateSalt());
            //将原始密码进行加密,配合盐再次加密,防止破解
            user.setPassword(Md5Utils.md5Hex(user.getPassword(),
                    user.getSalt()));
            //如果返回结果1为成功,0为失败
            return userMapper.insertSelective(user) == 1;
        }
        return false;
    }

    public Boolean Vercode(String phone,String code){
        //获取redis key值
        String key = KEY_PREFIX + phone;
        //通过key获取验证码
        String cod = this.redisTemplate.opsForValue().get(key);

        if(code.equals(cod)){
            return true;
        }

        return false;
    }


    public Boolean Veriphone(User user){

        User ex=userMapper.selectOne(user);
        if(ex.getPhone().equals(user.getPhone())){
            //获取redis key值
            String key = KEY_PREFIX + ex.getPhone();
            //通过key获取验证码
            String cod = this.redisTemplate.opsForValue().get(key);
            if(user.getCode().equals(cod)){
                return true;
            }else {
                return false;
            }
        }
        return false;
    }

    public  User query(String username,String password){
        User ex=new User();
        ex.setUsername(username);
        User user=userMapper.selectOne(ex);
        //根据用户名查询用户，校验用户名，密码是否正确
        if(user==null){
            return null;
            //原始密码加盐加密后，在与数据库密码进行对比
        } else if(!user.getPassword().equals(Md5Utils.md5Hex(password,user.getSalt()))){
            return null;
        }
        return user;
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final String KEY_PREFIX = "user:code:phone:";

    static final Logger logger = LoggerFactory.getLogger(UserService.class);

    public Boolean sendVerifyCode(String phone) {

        //生成验证码
        String code = NumberUtils.generateCode(6);

        try {
            // 发送短信
            Map<String,String> msg = new HashMap<>();
            msg.put("phone",phone);
            msg.put("code",code);
            System.out.println(msg);
            //把手机号，验证码放到队列里
            amqpTemplate.convertAndSend("b2c.sms.exchange","sms.verify.code",msg);
            // 将code存入redis 设置实现时间
            redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            return true;
        }catch (Exception e){
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }


    }
    public void put(User user) {

        User ex=new User();
        ex.setUsername(user.getUsername());
        User us=userMapper.selectOne(ex);
        ex.setId(us.getId());
        ex.setSalt(us.getSalt());
        ex.setPassword(Md5Utils.md5Hex(user.getPassword(),us.getSalt()));
        userMapper.updateByPrimaryKeySelective(ex);
    }

    public void shou(User user) {

        User ex=new User();
        ex.setUsername(user.getUsername());
        User us=userMapper.selectOne(ex);
        ex.setId(us.getId());
        ex.setSalt(us.getSalt());
        ex.setPassword(us.getPassword());
        ex.setPhone(user.getPhone());
        userMapper.updateByPrimaryKeySelective(ex);
    }

}
